#For 183read
from PIL import Image
import os
import requests
#请在C盘根目录下创建python文件夹
#其他OS，请在相应路径创建对应目录，并将IMAGES_PATH改为对应目录，
#如统信UOS在Home目录下新建python文件夹
IMAGES_PATH = '/home/YourName/python/'
dt_info = {}
dt_page = {}
dirname =  input("请输入文件夹名: ")
page = input("请输入总页数")
print("magazine/29/37729/20/918520/")
print("magazine/29/37729/常量随刊名变化")
print("                 /20/918520/变量随期数变化")
mainsite = input("请输入参数29/37729/20/918520/")
path = os.path.join(IMAGES_PATH,dirname)
if not os.path.exists(path):
    os.mkdir(path)
#请读者自行将***改为文章第四节中链接中的“https://服务器域名/data/magazine/”部分，注意不含后续路径及文件名
constanturl = "https://***/data/magazine/"
mainurl = constanturl + mainsite + "900/"
dt_page[page] = int(page) + 1
imgwith = 0
imghigh = 0
block_info = []
blockno = 16
#建立单个页面的存储文件夹并下载
for pagefd in range(1, dt_page[page], 1):
    blockwith = 0
    blockhigh = 0
#    block_info.clear()
    if pagefd < 10:
        ppath = os.path.join(path,'00' + str(pagefd))
        fgpath = ppath + '.jpeg'
        urlwithepageinfo = mainurl + '0/' + str(pagefd) + '/000'+ str(pagefd) + '_'
    elif pagefd < 100:
        ppath = os.path.join(path,'0' + str(pagefd))
        fgpath = ppath + '.jpeg'
        up10 = pagefd // 10 % 10
        up1 = pagefd % 10
        urlwithepageinfo = mainurl + str(up10) + '/' + str(up1) +  '/00' + str(pagefd) + '_'
    else :
        ppath = os.path.join(path, str(pagefd))
        fgpath = ppath + '.jpeg'
        up10 = pagefd // 10 % 10
        up1 = pagefd % 10
        urlwithepageinfo = mainurl + str(up10) + '/' + str(up1) + '/0' + str(pagefd) + '_'
    if not os.path.exists(ppath):
        os.mkdir(ppath)
    pginfo = 'page/' + str(pagefd)
    print("")
    XC = 3 #此变量后续图片块行拼接计数用

    #单页图片块下载
    blockx = 0
    blocky = 1
    for blockdlcnt in range(1, blockno, 1):
        if blockx < 3:
            blockx = blockx + 1
        else:
            blockx = 1
            if blocky <= 5:
                blocky = blocky + 1
        url = urlwithepageinfo + str(blocky) + '_' + str(blockx) + '.jpg'
        imgname = str(blocky) + str(blockx) + '.jpg'
        filepath = os.path.join(ppath, imgname)

        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'}

        if os.path.isfile(filepath):
            print(filepath, 'File Exist!')
        else:
            try:
                print('Downloading...', filepath)
                response = requests.get(url, headers=headers)
                response.raise_for_status()
                with open(filepath, 'wb') as f:
                    f.write(response.content)
                    f.flush()
            except Exception as exc:
                print('%s' % (exc))
        if int(blockx) == 1:
            if int(blocky) <= 5:
                blockhigh = Image.open(filepath).size[1] + blockhigh
        if int(blocky) == 5:
            if int(blockx) <= 3:
                blockwith = Image.open(filepath).size[0] + blockwith

    imgwith = blockwith
    imghigh = blockhigh
    comimg = Image.new('RGB', (imgwith, imghigh))
    imgcnt = 0
    position = [0, 0]
    YC = 5
    position[0] = 0
    position[1] = 0
    for X in range(1, (XC+1)):
        for Y in range(1, (YC+1)):
            sigleimage = Image.open(os.path.join(ppath, str(Y) + str(X) + '.jpg'))
            comimg.paste(sigleimage, (position[0], position[1]))
            position[1] = position[1] + sigleimage.size[1]
        position[1] = 0
        position[0] = position[0] + sigleimage.size[0]
    comimg.save(fgpath)